﻿using System;

using Microsoft.AspNetCore.Http;

namespace zijian666.WebApi
{
    /// <summary>
    /// WebApi选项组
    /// </summary>
    public partial class WebApiOptions
    {
        /// <summary>
        /// TraceId生成器
        /// </summary>
        protected Func<HttpContext, string>? TraceIdBuilder { get; private set; }

        /// <summary>
        /// 启用上下文跟踪id
        /// </summary>
        /// <param name="builder"></param>
        public void EnableTraceIdentifier(Func<HttpContext, string> builder) => TraceIdBuilder = builder;

        /// <summary>
        /// 启用上下文跟踪id,自动使用请求头中的X-Correlation-ID或X-Request-ID作为跟踪id,如果不存在则创建一个guid
        /// </summary>
        public void EnableTraceIdentifier()
        {
            TraceIdBuilder = context =>
            {
                if (context.Request.Headers.TryGetValue("X-Correlation-ID", out var header)
                 || context.Request.Headers.TryGetValue("X-Request-ID", out header))
                {
                    var traceId = header.ToString();
                    if (!string.IsNullOrWhiteSpace(traceId))
                    {
                        return traceId;
                    }
                }
                return Guid.NewGuid().ToString("n");
            };
        }

        /// <summary>
        /// 填充 <seealso cref="HttpContext.TraceIdentifier"/>
        /// </summary>
        private partial void FillTraceIdentifier(HttpContext context)
        {
            if (TraceIdBuilder is not null)
            {
                context.TraceIdentifier = TraceIdBuilder(context);
            }
        }
    }
}
